package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.SysUserPush;
import com.ruoyi.system.mapper.*;
import com.ruoyi.system.service.ISysUserPushService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户小程序openid绑定 业务层
 *
 * @author ruoyi
 */
@Service
public class SysUserPushServiceImpl implements ISysUserPushService {
    private static final Logger log = LoggerFactory.getLogger(SysUserPushServiceImpl.class);

    @Autowired
    private SysUserPushMapper userPushMapper;

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SysUserPush selectUserPushById(Long userId) {
        return userPushMapper.selectUserPushById(userId);
    }

    /**
     * 功能描述:    绑定用户小程序推送信息，同时openid解绑其他账号
     *
     * @Author wanghc
     * @Date 2022/08/21 16:03
     * @param userPush 用户绑定openid
     * @return void
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserPush(SysUserPush userPush) {
        SysUserPush sysUserPush = userPushMapper.selectUserPushById(userPush.getUserId());
        if(sysUserPush == null){
            // 第一次登录默认开启报警推送
            userPush.setOpen(1);
            userPushMapper.insertUserPush(userPush);
        }else{
            userPushMapper.updateUserPush(userPush);
        }
        // 小程序解绑其他非当前登录账号而绑定该openid的账号
        userPushMapper.updateUnBundOpenid(userPush.getOpenid(), userPush.getUserId());
    }

    /**
     * 新增保存用户openid绑定信息
     *
     * @param userPush 用户信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertUserPush(SysUserPush userPush) {
        // 新增用户绑定信息
        int rows = userPushMapper.insertUserPush(userPush);
        return rows;
    }

    /**
     * 修改保存用户openid绑定信息
     *
     * @param userPush 用户openid绑定信息
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUserPush(SysUserPush userPush) {
        return userPushMapper.updateUserPush(userPush);
    }

    /**
     * 通过用户ID删除用户绑定信息
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserPushById(Long userId) {
        return userPushMapper.deleteUserPushById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteUserPushByIds(Long[] userIds) {
        return userPushMapper.deleteUserPushByIds(userIds);
    }

}
